#include "comm.h"

int main(int argc, char **argv)
{
    int msqid;
	struct msqid_ds info;
    struct MsgType msg;
    int flag = 0 ;
    int pid ;	
	
	msqid = msgget(IPC_PRIVATE,SVMSG_MODE|IPC_CREAT);
    if(msqid < 0){
        perror("msgget() error");
        return -1 ;
    }	

    pid = fork() ;

    if ( pid == 0 )
    {
		int i = 0;
		while(i < atoi(argv[1]))
		{
			msg.len = -1;
			memset(msg.buf, 0, MAXSIZE);
			msg.x = ' ';
			msg.y = -1;
	 
			/* getting a message */
			if (msgrcv(msqid, (char*)&msg, sizeof(struct MsgType),0,0) == -1) 
			{
				perror("msgrcv() error");
				return -1 ;
			}

			flag = msgctl( msqid, IPC_STAT, &info) ;
			if ( flag == -1 )
			{
				perror("msgctl() error") ;
				return -1 ;
			}
			//printf("msg_qbytes =%d bytes\n",(int)info.msg_qbytes);
			//printf("msgsnd_pid = %d \n",info.msg_lspid);
			//printf("msgrcv_pid = %d \n",info.msg_lrpid);

			printf("chlid pid=%d, msg.len = %d, msg.buf = %s, msg.x = %c, msg.y = %d msgsnd_pid = %d msgrcv_pid = %d\n",(int)getpid(), msg.len, msg.buf, msg.x, msg.y, info.msg_lspid, info.msg_lrpid);

			i++;
			sleep(1); 
		}
		return 0;
	} else if ( pid > 0) {
		printf("parent pid=%d\n", (int)getpid()) ;
		printf("chlid pid=%d\n",pid) ;
		
		int i = 0; 
		while(i < atoi(argv[1])) 
		{
			msg.len = i;
			memset(msg.buf, 0, MAXSIZE);
			sprintf(msg.buf, "0x%x", i);
			msg.x = (char)(i + 'a');
			msg.y = (short)(i + 100);

			printf("parent pid=%d, msg.len = %d, msg.buf = %s, msg.x = %c, msg.y = %d\n",(int)getpid(), msg.len, msg.buf, msg.x, msg.y);

			/*sending the message      --  mq_send() */
			if(msgsnd(msqid, (char*)&msg, sizeof(struct MsgType), 0) == -1)
			{
				perror("msgsnd() error");
				exit(1);
			}

			i++;
			sleep(1);   
		}
		destroy_msq(msqid);
	}else{
        perror("fork error");
		destroy_msq(msqid);
    }	
	return 0;
}
